/*
 * Copyright (c) 2015. kupat Corporation. All rights reserved.
 *  see statement on http://www.kupat.cn.
 */
package com.kfgj.hkp.common.components.io;

import java.nio.ByteBuffer;

/**
 * 自动扩展的ByteBuffer
 * 如果需要重新写入的话，需要调用clear方法
 * @author David Cun
 *
 */
public class AutoExtendByteBuffer {

	private ByteBuffer btb;
	private static final int defaultCapacity=1024;
	public AutoExtendByteBuffer() {
		btb = ByteBuffer.allocate(defaultCapacity);
	}
	public AutoExtendByteBuffer(int capacity){
		btb = ByteBuffer.allocate(capacity);
	}
	public void append(byte bt){
		this.append(new byte[]{bt}, 0, 1);
	}
	public void append(byte[] bts){
		this.append(bts,0,bts.length);
	}
	
	public void append(byte[] bts,int offset,int length){
		ensureCapacity(btb.position()+bts.length);
		btb.put(bts, offset, length);
	}
	
	public void append(ByteBuffer bb){
		bb.flip();
		ensureCapacity(bb.limit()+btb.position());
		btb.put(bb);
	}
	public byte[] getBytes(){
		int position = btb.position();
		int limit = btb.limit();
		btb.flip();
		byte[] bt = new byte[position];
		btb.get(bt);
		btb.position(position);
		btb.limit(limit);
		return bt;
	}
	public ByteBuffer getBuffer(){
		return ByteBuffer.wrap(getBytes());
	}
	public void clear(){
		btb.clear();
	}
	public void ensureCapacity(int minapacity){
		if (minapacity >= (btb.capacity()-btb.capacity()/5)) {
			ByteBuffer tmp = ByteBuffer.allocate(minapacity + minapacity/5);
			tmp.clear();
			btb.flip();
			tmp.put(btb);
			btb = tmp;
		}
	}

}
